package cn.gdcp.mediatest;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FilterQueryProvider;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.security.Provider;

public class MainActivity extends AppCompatActivity {
       Button takePhoto;
       ImageView photo;
       Button choosePhoto;
    Uri uri;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        takePhoto=findViewById(R.id.take_photo);
        photo=findViewById(R.id.photo);
        //拍照
        /**
         * 先获得获得sd卡当前应用的临时缓存位置
         * 调用getExternalCacheDir获得这个目录，然后创建文件
         * 再将文件转换成uri（转换时需要进行版本判定）
         * 启动意图进行拍照，将uri作为参数传入
         * 回调到onActivityForResult(resultCode=RESULTOK说明拍照完成)
         * uri转换成位图
         */
              getImgUri();
           takePhoto.setOnClickListener(new View.OnClickListener() {
               public void onClick(View v) {
                   startTakePhoto();
               }
           });
                choosePhoto=findViewById(R.id.choose_photo);
            choosePhoto.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    //判断用户之前有没有授权
                 if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.WRITE_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED){
                     ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},2);
                 }
                        else{
                        openAlbum();
                    }
                }
            });
    }

    /**
     * 打开相册
     *  intent.setType("image/*");
     */
         private  void openAlbum(){
           Intent intent=new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
           startActivityForResult(intent,3);
  }

    public void onRequestPermissionsResult(int requestCode,  String[] permissions, int[] grantResults)   {
            if (requestCode==2) {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                {
                    openAlbum();
                }else {
                    Toast.makeText(MainActivity.this, "没有授权", Toast.LENGTH_SHORT).show();
                }
            }

    }



    private void displayImage(String imagePath) {
        if (imagePath!=null){
               Bitmap bitmap=BitmapFactory.decodeFile(imagePath);
               photo.setImageBitmap(bitmap);
        }else{
            Toast.makeText(this, "无法获取到图片", Toast.LENGTH_SHORT).show();
        }

    }

    private String getImagePath(Uri uri, String selection) {
                 String path=null;
        Cursor cursor=getContentResolver().query(uri,null,selection,null,null);
      if (cursor!=null){
          if (cursor.moveToFirst())
          {  path=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
          }
          cursor.close();
      }
                  return path;
    }

    /**
     * 不同版本处理选取照片的uri
     */

    @TargetApi(19)
    private void handleImageOnKitKat(Intent data) {
                  String imagePath=null;
                  Uri uri=data.getData();
                  if (DocumentsContract.isDocumentUri(this,uri)){
                   String docId=DocumentsContract.getDocumentId(uri);
                   if ("com.android.providers.media.documents".equals(uri.getAuthority())){
                       String selection=docId.split(":")[1];
                       imagePath=getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
                   }else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())){
                       Uri contentUri= ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(docId));
                       imagePath=getImagePath(contentUri,null);
                   }
                  }
                  else if("content".equalsIgnoreCase(uri.getScheme())){
                      imagePath=getImagePath(uri,null);
                  }
                  else if("file".equalsIgnoreCase(uri.getScheme())){
                      imagePath=uri.getPath();
                  }
                  displayImage(imagePath);
    }
    private void handleImageBeforeKitKat(Intent data) {
        Uri uri=data.getData();
        String imagePath=getImagePath(uri,null);
        displayImage(imagePath);
    }
    /**
     * 获得文件的uri
     */
    public void getImgUri() {
        File outputImg=new File(getExternalCacheDir(),"output_img.jpg");
        try {
            if (outputImg.exists()){
                outputImg.delete();
            }
            outputImg.createNewFile();
        }catch (IOException e){
            e.printStackTrace();
        }
        if (Build.VERSION.SDK_INT>=24){
             uri= FileProvider.getUriForFile(this,"cn.gdcp.mediatest.provider",outputImg);
        }else {
            uri=uri.fromFile(outputImg);
               }
        }
    private void startTakePhoto() {
        Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT,uri);
        startActivityForResult(intent,11);
    }
    protected void onActivityResult(int requestCode, int resultCode,  Intent data) {
        switch (requestCode){
            case 11:
                Log.e("111","3333");
                if (resultCode==RESULT_OK){
                    Log.e("111","2222");
                    Bitmap bitmap=null;
                    try {
                       bitmap=BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
                    }
                    catch (IOException e){
                        e.printStackTrace();
                    }
                    photo.setImageBitmap(bitmap);

                }
                break;
            case 3:
                /**
                 * android从4.4开始选取的相册不再返回真是的uri
                 */
                if (resultCode==RESULT_OK)
                {
                    if (Build.VERSION.SDK_INT>=19){
                        handleImageOnKitKat(data);
                    }
                    else {
                        handleImageBeforeKitKat(data);
                    }
                }
                break;

        }

    }

    }
